import router from './router'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/user'
import { usePermissionStore } from '@/store/permission'
import { ElMessage } from 'element-plus'
import getPageTitle from '@/utils/get-page-title'
// import { getPageTitle } from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/auth-redirect']

// 添加一个标志来跟踪路由是否已加载
window.hasRoutes = false

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  // document.title = getPageTitle(to.meta.title)
  document.title = '测试'
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        // 只有在路由未加载时才加载菜单
        if (!window.hasRoutes) {
          const permissionStore = usePermissionStore()
          const routes = await permissionStore.loadMenu()
          
          // Add routes dynamically
          routes.forEach(route => {
            router.addRoute(route)
          })
          
          window.hasRoutes = true
          // 添加完路由后，需要重新进入当前路由
          next({ ...to, replace: true })
        } else {
          next()
        }
      } catch (error) {
        const userStore = useUserStore()
        await userStore.resetToken()
        ElMessage.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
}) 